package com.whatever;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.ProgressBar;
import android.widget.Toast;

public class MenuPracticeActivity extends Activity {
    
	public Context cxt = this;
	public ProgressBar progressBar;
	public Handler threadHandler = new Handler(){ 
    	@Override 
    	public void handleMessage(Message msg) {
    		progressBar.incrementProgressBy(1);
    	}
	};
	public Thread thread1;
	public boolean isRunning = false;
	public static boolean shouldPause = false;
	
	/** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        progressBar = (ProgressBar)findViewById(R.id.progressBar0);
    }
    
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
    	MenuInflater inflater = getMenuInflater();
    	inflater.inflate(R.menu.newmenu, menu);
    	return true;
    }
    
    @Override
    public boolean onOptionsItemSelected(MenuItem menuItem) {
    	switch(menuItem.getItemId()) {
    	case(R.id.item0):
    		isRunning = true;
	    		thread1.start();
	    		shouldPause = false;
	    	return true;
    	case(R.id.item1):
    		isRunning = false;
    		shouldPause = true;
    		return true;
    	default:
    		return super.onOptionsItemSelected(menuItem);
    	}
    }
    
    @Override
    public void onStart() {
    	super.onStart();
    	progressBar.setProgress(0);
    	Thread background = new Thread(new Runnable() {
    		public void run() {
				try{
					for(int i = 0; i < 100 && isRunning; i++) {
						if(shouldPause) {
							thread1.wait();
						} else {
							Thread.sleep(100);
							threadHandler.sendMessage(threadHandler.obtainMessage());
						}
					}
				}catch(Exception e) {
					System.out.println(e);
				}
			}
    	});
    	thread1 = background;
    }
    
    @Override
    public void onStop() {
    	super.onStop();
    	isRunning = false;
    }
}